package com.wechat.service.quartz.config;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.wechat.service.quartz.bo.InitJobBo;
import com.wechat.service.quartz.job.AbstractJob;
import com.wechat.service.quartz.service.IJobService;



@Component
public class StartJob implements CommandLineRunner {
	private final static Logger log = LoggerFactory.getLogger(StartJob.class);
	@Autowired
	private InitJob initJob;
	@Autowired
	private ApplicationContext applicationContext;
	@Autowired(required = false)
	private IJobService jobService;

	@Override
	public void run(String... arg0) throws Exception {
		
		@SuppressWarnings("unused")
		Map<String, AbstractJob> beansOfType = applicationContext.getBeansOfType(AbstractJob.class);
		
		if(beansOfType == null) return;
		
		ArrayList<InitJobBo> listg = new ArrayList<InitJobBo>();
		List<InitJobBo> allJob = null;
		if (jobService != null) {
			allJob = jobService.getAllJob();
			allJob = allJob == null ? new ArrayList<InitJobBo>() : allJob;
		} else {
			log.warn("IJobService 需要一个实现类");
		}
		for (AbstractJob abstractJob : beansOfType.values()) {
			boolean falg = false;
			for (InitJobBo initJobBo : allJob) {
				if (initJobBo.getTaskName().equals(abstractJob.getTaskName())
						&& initJobBo.getTaskGroup().equals(abstractJob.getTaskGroup())) {

					InitJobBo dBJobBo = new InitJobBo();
					dBJobBo.setClassName(initJobBo.getClassName());
					dBJobBo.setTaskCron(initJobBo.getTaskCron());
					dBJobBo.setTaskDesc(initJobBo.getTaskDesc());
					dBJobBo.setTaskGroup(initJobBo.getTaskGroup());
					dBJobBo.setTaskName(initJobBo.getTaskName());
					dBJobBo.setTaskRun(initJobBo.getTaskRun());
					listg.add(dBJobBo);
					falg = true;
					break;
				}
			}
			if (!falg) {
				InitJobBo classJobBo = new InitJobBo();
				classJobBo.setClassName(abstractJob.getClassName());
				classJobBo.setTaskCron(abstractJob.getTaskCron());
				classJobBo.setTaskDesc(abstractJob.getTaskDesc());
				classJobBo.setTaskGroup(abstractJob.getTaskGroup());
				classJobBo.setTaskName(abstractJob.getTaskName());
				classJobBo.setTaskRun(abstractJob.isTaskRun());
				listg.add(classJobBo);
			}
		}
		initJob.init(listg);
		
		jobService.saveAll(listg);
		
	}

}
